#include "InputManager.h"

InputManager* InputManager::instance;

InputManager::InputManager()
{
    keyState = SDL_GetKeyState(NULL);
    SDL_PumpEvents();
}

bool InputManager::isKeyDown(int key)
{
    for(vector<Uint8>::iterator it = keyDownState.begin();
                it != keyDownState.end(); it++)
    {
        Uint8 keyArray = *it;
        if(keyArray == key)
        {
            keyDownState.erase(it);
            return true;
        }
    }
    return false;
}

bool InputManager::isKeyUp(int key)
{
    for(vector<Uint8>::iterator it = keyUpState.begin();
                it != keyUpState.end(); it++)
    {
        Uint8 keyArray = *it;
        if(keyArray == key)
        {
            keyUpState.erase(it);
            return true;
        }
    }
    return false;
}

bool InputManager::isKeyPressed(int key)
{
    return keyState[key];
}

bool InputManager::isMouseDown(int button)
{
    for(vector<Uint8>::iterator it = mouseDownState.begin();
                it != mouseDownState.end(); it++)
    {
        Uint8 mouseArray = *it;
        if(mouseArray == button)
        {
            mouseDownState.erase(it);
            return true;
        }
    }
    return false;
}

bool InputManager::isMouseUp(int button)
{
    for(vector<Uint8>::iterator it = mouseUpState.begin();
                it != mouseUpState.end(); it++)
    {
        Uint8 mouseArray = *it;
        if(mouseArray == button)
        {
            mouseUpState.erase(it);
            return true;
        }
    }
    return false;
}

bool InputManager::isMousePressed(int button)
{
    return keyState[button];
}

int InputManager::mousePosX()
{
    return x;
}

int InputManager::mousePosY()
{
    return y;
}

bool InputManager::isMouseInside(Sprite *sprite)
{
    SDL_Rect rect = sprite->GetRect();

    if(((mousePosX() >= rect.x) && (mousePosX() <= (rect.x + rect.w))) && ((mousePosY() <= rect.y) && (mousePosY() >= (rect.y + rect.h) )))
        return true;
    else
        return false;
}

InputManager* InputManager::getInstance()
{
    if(instance == NULL)
        instance = new InputManager();

    return instance;
}

bool InputManager::Update()
{
    SDL_GetMouseState(&x,&y);
    SDL_Event event;
    quit = false;
    while (SDL_PollEvent(&event))
    {
        if(event.type == SDL_KEYDOWN)
            keyDownState.push_back(event.key.keysym.sym);

        else if(event.type == SDL_KEYUP)
            keyUpState.push_back(event.key.keysym.sym);

        else if(event.type == SDL_MOUSEBUTTONUP)
            mouseUpState.push_back(event.button.button);

        else if(event.type == SDL_MOUSEBUTTONDOWN)
            mouseDownState.push_back(event.button.button);
        else if(event.type == SDL_QUIT){
            quit = true;
        }
    }
    return quit;
}
